package com.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 全局过滤器，所有请求都会经过
 */
@Slf4j
@Component
public class RtGlobalFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        final URI uri = request.getURI();
        log.info("RtGlobalFilter 过滤器开始执行,当前请求url {}",  uri);
        final long startTime = System.currentTimeMillis();
        // 执行请求 因为响应式网关会立刻返回，所以需要在响应式网关执行完所有过滤器后，再执行doFinally方法
        Mono<Void> filter = chain.filter(exchange).doFinally(result -> {
            long endTime = System.currentTimeMillis();
            log.info("RtGlobalFilter 过滤器请求处理完成,当前请求url {}，耗时 {} ms",  uri, endTime - startTime);
        });
        // 结束时间不能在这里获取，因为响应式网关会立刻返回，所以需要在响应式网关执行完所有过滤器后，再执行doFinally方法
        //long endTime = System.currentTimeMillis();
        log.info("RtGlobalFilter 过滤器结束执行,当前请求url {}",  request.getURI());
        return filter;
    }

    /**
     * 优先级，值越小，优先级越高(最先执行)
     * @return
     */
    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }
}
